import { TASK_KEY_LABEL_MAP } from '../../../common/constants';
import errorCodesBuilder from '../../helpers/errorCodesBuilder';

const errorCodes = errorCodesBuilder('重新执行监测任务失败');

export default {
	description: '重新执行监测任务',
	type: 'Task',
	args: {
		taskId: 'MongoID!',
	},
	async resolve(root, { taskId }, { request }) {
		const {
			server: {
				methods: { createOrUpdateTask },
				app: { model },
			},
			auth: {
				credentials: { uid, permissionMap },
			},
		} = request;

		let task;
		let note = '';
		try {
			const query = { _id: taskId };
			if (!permissionMap[`cloud-monitor\x01editTask\x010`]) {
				query.uid = uid;
			}
			task = await model.Task.findOne(query).populate({
				path: 'jobId',
				populate: { path: 'jobId' },
			});
			note = task.jobId.note;
			if (!task) {
				throw new Error(`retryTask: not found task ${task} with uid ${uid}`);
			}
		} catch (err) {
			const error = errorCodes['[01]重试任务:查找任务mongo记录失败'].from(err);
			request.log.error({ error }, error.rawMessage);
			throw error;
		}

		try {
			await createOrUpdateTask({
				taskType: task.taskType,
				triggerType: 'manual',
				body: {
					taskSettings: task.taskSettings,
					jobId: task.jobId?._id,
					enableMonitor: true,
					immediateExec: true,
					addition: {
						pk: task._id,
					},
				},
			});
		} catch (err) {
			const error = errorCodes['[01]重试监测任务失败'].from(err);
			request.log.error({ error }, error.rawMessage);
			throw error;
		}

		request.log.audit(
			{
				affects: [task.target],
				module: 'task',
				actionType: 'update',
				actionMessage: `更新${TASK_KEY_LABEL_MAP[task.taskType]}监测任务`,
				detail: `重试${
					TASK_KEY_LABEL_MAP[task.taskType]
				}监测任务队列中资产名称为${note}的监测任务。`,
			},
			`[${task.target}]重试监测任务`
		);

		return task;
	},
};
